import utils from '../core/utils';
import logger from '../core/logger';
import appClient from '../api/appClient';
import dict, { HOST } from '../core/dict';
import common from '@ohos.app.ability.common';
import formItem from '../models/cards/formItem';
import cardItem from '../models/cards/cardItem';
import formProvider from '@ohos.app.form.formProvider';
import relationalStore from '@ohos.data.relationalStore';
import formBindingData from '@ohos.app.form.formBindingData';

class cardManager {
  async createRdbStore(context: common.Context): Promise<relationalStore.RdbStore> {
    try {
      if (utils.isEmpty(globalThis.rdbStore)) {
        await relationalStore.getRdbStore(context, dict.STORE_CONFIG).then((rdbStore: relationalStore.RdbStore) => {
          if (!utils.isEmpty(rdbStore)) {
            rdbStore.executeSql(dict.CARD_TABLE_FORM);
            rdbStore.executeSql(dict.FORM_TABLE_FORM);
            globalThis.rdbStore = rdbStore;
          }
        });
      }
    } catch (e) {
      logger.error(e);
    }
    return globalThis.rdbStore;
  }

  insertForm(form: formItem, rdbStore: relationalStore.RdbStore) {
    try {
      if ((utils.isEmpty(rdbStore)) || (utils.isEmpty(form)))
        return;
      rdbStore.insert(dict.FORM_NAME, form.toValuesBucket())
        .then((res) => logger.info(`add form card return ${res}`))
        .catch((err) => logger.error(err));
    } catch (e) {
      logger.error(e);
    }
  }

  startTimer() {
    try {
      let rdbStore: relationalStore.RdbStore = globalThis.rdbStore;
      this.updateCardData(rdbStore);
      if (utils.isEmpty(globalThis.intervalId)) {
        globalThis.intervalId = setInterval(() => {
          this.updateCardData(rdbStore);
        }, dict.INTERVAL_DELAY_TIME);
      }
    } catch (e) {
      logger.error(e);
    }
  }

  updateCardData(rdbStore: relationalStore.RdbStore) {
    try {
      if (!utils.isEmpty(rdbStore)) {
        this.getListData().then((listData) => {
          if (listData.length > 0) {
            this.getFormData(listData).then((formData) => {
              let predicates: relationalStore.RdbPredicates = new relationalStore.RdbPredicates(dict.FORM_NAME);
              rdbStore.query(predicates).then((resultSet: relationalStore.ResultSet) => {
                if (resultSet.rowCount > 0) {
                  resultSet.goToFirstRow();
                  do {
                    let formId: string = resultSet.getString(resultSet.getColumnIndex('formId'));
                    formProvider.updateForm(formId, formBindingData.createFormBindingData(formData))
                  } while (resultSet.goToNextRow());
                  resultSet.close();
                }
              });
            });
          }
        });
      }
    } catch (e) {
      logger.error(e);
    }
  }

  deleteFormData(formId: string, rdbStore: relationalStore.RdbStore) {
    try {
      if (!utils.isEmpty(rdbStore)) {
        let predicates: relationalStore.RdbPredicates = new relationalStore.RdbPredicates(dict.FORM_NAME);
        predicates.equalTo('formId', formId);
        rdbStore.delete(predicates);
      }
    } catch (e) {
      logger.error(e);
    }
  }

  loadData() {
    try {
      let rdbStore: relationalStore.RdbStore = globalThis.rdbStore;
      appClient.getUpdate().then((res) => {
        if (res.success) {
          this.clear();
          res.data.forEach((i) => {
            var obj = {
              'aid': i.id,
              'name': i.name,
              'cover': i.icon,
              'desc': `${i.typeName}/${i.typeName}`
            };
            rdbStore.insert(dict.CARD_TABLE_NAME, obj)
              .catch((err) => logger.error(err));
          });
        }
      });
    } catch (e) {
      logger.error(e);
    }
  }

  getListData(): Promise<cardItem[]> {
    return new Promise((resolve) => {
      let array = [];
      let rdbStore: relationalStore.RdbStore = globalThis.rdbStore;
      try {
        let predicates: relationalStore.RdbPredicates = new relationalStore.RdbPredicates(dict.CARD_TABLE_NAME);
        rdbStore.query(predicates).then((resultSet: relationalStore.ResultSet) => {
          if (resultSet.rowCount > 0) {
            resultSet.goToFirstRow();
            do {
              let aid: string = resultSet.getString(resultSet.getColumnIndex('aid'));
              let name: string = resultSet.getString(resultSet.getColumnIndex('name'));
              let cover: string = resultSet.getString(resultSet.getColumnIndex('cover'));
              let desc: string = resultSet.getString(resultSet.getColumnIndex('desc'));
              array.push(new cardItem(aid, name, cover, desc));
            } while (resultSet.goToNextRow());
            resultSet.close();
          }
          resolve(array);
        }).catch((res) => {
          logger.error(res);
          resolve(array);
        });
      } catch (e) {
        logger.error(e);
        resolve(array);
      }
    });
  }

  getFormData(dataSource: cardItem[]) {
    return new Promise((resolve) => this.toFormData(dataSource).then((res) => resolve(res)));
  }

  private toFormData(dataSource: cardItem[]): Promise<object> {
    return new Promise((resolve) => {
      let formData = {};
      try {
        var length = dataSource.length;
        var start = utils.getRandomInt(length);
        if (start >= length) start = 0;
        var item = dataSource[start];
        let end = start + 1;
        if (end >= length) end = 0;
        var last = dataSource[end];
        let imgs = [`${HOST}images/${item.cover}`, `${HOST}images/${last.cover}`];
        utils.buildMemoryImage(globalThis.abilityContext, imgs).then((res) => {
          let fileInfo = {};
          let imageName = res[0].fileName, lastImageName = res[1].fileName;
          fileInfo[imageName] = res[0].fileId;
          fileInfo[lastImageName] = res[1].fileId;
          formData = {
            'aid': item.aid,
            'last_aid': last.aid,
            'title': item.name,
            'last_title': last.name,
            'describe': item.desc,
            'last_describe': last.desc,
            'formImages': fileInfo,
            'image': `memory://${imageName}`,
            'last_image': `memory://${lastImageName}`
          };
          resolve(formData);
        });
      } catch (e) {
        logger.error(e);
        resolve(formData);
      }
    });
  }

  private clear() {
    try {
      let rdbStore: relationalStore.RdbStore = globalThis.rdbStore;
      let predicates: relationalStore.RdbPredicates = new relationalStore.RdbPredicates(dict.CARD_TABLE_NAME);
      rdbStore.delete(predicates);
    } catch (e) {
      logger.error(e);
    }
  }
}
export default new cardManager();